<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.fileupload.util.Streams" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>

<%@ page import="unilearn.facade.FileFacade" %>
<%@ page import="unilearn.domain.DataFile" %>

<%@ page import="java.io.*" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>Upload testing</title>
	</head>
	<body>
		<h1>Upload page</h1>
		<%
			if (ServletFileUpload.isMultipartContent(request)) {
				// Create a factory for disk-based file items 
				FileItemFactory factory = new DiskFileItemFactory();

				// Create a new file upload handler
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setFileSizeMax(1048576); // Maximum upload 10MB

				try {
					// Parse the request
					List items = upload.parseRequest(request);

					Iterator iter = items.iterator();
					while (iter.hasNext()) {
						DiskFileItem item = (DiskFileItem) iter.next();

						if (item.isFormField()) {
							out.println("Form field \"" + item.getFieldName() + "\" with value \"" + item.getString() + "\" detected.<br />");
						} else {
							try {
								File tempFile = File.createTempFile("upload", ".tmp");
								item.write(tempFile);

								DataFile uploadedFile = new DataFile();
								uploadedFile.setFileName(item.getName());
								uploadedFile.setFileType(item.getContentType());
								uploadedFile.setFileSize(item.getSize());
								uploadedFile.setFile(tempFile);

								long fileid = FileFacade.insertFile(uploadedFile);
								tempFile.delete(); // delete temp file from disk after blob has been inserted

								out.println(item.getName() + " with fileid = " + fileid + " uploaded successfully<br />");

							} catch (SQLException e) {
								out.println(e.getMessage());
							} catch (NamingException e) {
								out.println(e.getMessage());
							} catch (IOException e) {
								out.println(e.getMessage());
							}
						}
					}
				} catch (Exception e) {
					out.println(e.getMessage());
				}
			}
		%>
		<form method="POST" action="upload.jsp" enctype="multipart/form-data">
			<!--Student id: <input type="text" name="student_id" ><br />-->
			Assignment: <input type="file" name="file_upload" /><br />
			<input type="submit" value="submit" />
		</form>
	</body>
</html>
